<template>
  <div class="bi-page">
    <div class="bi-breadcrumb" >
      <div class="bi-el-breadcrumb-line"></div>
      <el-breadcrumb class='bi-el-breadcrumb'  separator=">">
        <el-breadcrumb-item><span class="breadcrumb-node breadcrumb-root" @click="backToIndex" :class="breadcrumbItems.length ===  0 ? 'not-allow-click' : ''">我的申请</span></el-breadcrumb-item>
        <el-breadcrumb-item v-for="(item,index) in  breadcrumbItems" :key="index">
          <span class="breadcrumb-node" v-text="item.title"></span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div v-show="!createDataQueryRequestViewVisible && !dataQueryAuditDetailInfoViewVisible" style="overflow: auto;width: 100%;">
      <div  style="min-width: 1280px;">
        <div id="topOperate" label-width="120px" style="padding-left: 12px" class="bi-toolbar">
          <el-button size="mini" class="bi-el-btn "   @click="createQuery" >新建申请</el-button>
          <el-button size="mini" class="bi-el-btn "   @click="batchSubmit" >提交</el-button>
          <el-button  size="mini" class="bi-el-btn " @click="batchDelete">删除</el-button>
        </div>
        <el-form id="fliterForm" :inline="true" :model="filterForm"  ref="filterForm" class="bi-toolbar" style="line-height: 40px;height: 40px !important;padding-left: 16px;white-space: nowrap;">
          <el-form-item  label="审批状态" prop="statusList">
            <el-select style="width:340px;" v-model="filterForm.statusList" multiple placeholder="请选择">
              <el-option v-for="chck in statusList" :key="chck.label" :label="chck.title" :value="chck.label">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <section class="bi-panel bi-layout-content bi-layout-right-withoutLeft" style="height:calc(100% - 100px);max-width: 100%;width: 100%;">
          <el-table
              highlight-current-row
              border
              class="bi-el-table bi-el-table-edit"
              v-loading="loading"
              :max-height="height"
              :height="height"
              @row-click="tableRowClick"
              :data="queryList"
              ref="queryListTable">
            <el-table-column type="selection" width="40" align="center"></el-table-column>
            <el-table-column type="index" :index="indexMethod" label="序号" width="60" align="center"></el-table-column>
            <el-table-column prop="reqTime" label="申请时间" width="200" show-overflow-tooltip align="left"></el-table-column>
            <el-table-column label="申请资源数" width="100" align="left">
              <template slot-scope="scope">
                <el-button @click="numberInformationClick(scope.row.resGuid,scope.row.idaGuid)" type="text"   class="bi-el-btn-text" style="color: #0d54c5">{{scope.row.reqResourceNumber}}</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="validTime" label="申请有效期" width="200" align="left"></el-table-column>
            <el-table-column label="审批人" width="180" align="left">
              <template slot-scope="scope">
                {{scope.row.status === 10?' ':scope.row.auditUserTitle}}
              </template>
            </el-table-column>
            <el-table-column prop="statusTitle" label="审批状态" width="200" align="left"></el-table-column>
            <el-table-column prop="lastAuditTime" label="最后审批时间" width="200" align="left"></el-table-column>
            <el-table-column label="操作" fixed="right" min-width="150px">
              <template slot-scope="scope">
                <el-button type="text" size="small" class="bi-el-btn-text" @click="browseClick(scope.row,scope.$index)" v-if="scope.row.status !== 10" >查看</el-button>
                <el-button type="text" size="small" class="bi-el-btn-text" @click="modifyClick(scope.row,scope.$index)" v-if="scope.row.status === 10">编辑</el-button>
                <el-button type="text" size="small" class="bi-el-btn-text" @click="renew(scope.row,scope.$index)" v-if="scope.row.status === 30">续期</el-button>
                <el-button type="text" size="small" class="bi-el-btn-text" @click="submitPubClick(scope.row,scope.$index)" v-if="scope.row.status === 10">提交</el-button>
                <el-button type="text" size="small" class="bi-el-btn-text" @click="fetchBackClick(scope.row,scope.$index)" v-if="scope.row.status === 20">取回</el-button>
                <el-button type="text" size="small" class="bi-el-btn-text" @click="removeClick(scope.row,scope.$index)" v-if="scope.row.status === 10 || scope.row.status === 40">删除</el-button>
                <el-button type="text" size="small" class="bi-el-btn-text" @click="reSaveAndSubmit(scope.row,scope.$index)" v-if="scope.row.status === 40">再次申请</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
              class="bi-el-pagination"
              popper-class="bi-el-page-content"
              layout="total, prev, pager, next, jumper,sizes, slot"
              @size-change="pageSizeChange"
              @current-change="currentPageChange"
              :current-page="currPage"
              :page-sizes="[20, 50, 100]"
              :page-size="pageSize"
              :total="totalCount"
              align="right"></el-pagination>
        </section>
      </div>
    </div>
    <div v-if="createDataQueryRequestViewVisible"  class="bi-panel bi-layout-content" style="height: calc(100% - 60px);">
      <v-request-create
          ref="refOfcreateRequest"
          :linkageVisible.sync="createDataQueryRequestViewVisible"
          :idaGuid="currRow.idaGuid"
          :isAttachAction.sync="isAttachAction"
          :isDirty.sync="isDirty"
      >
      </v-request-create>
    </div>
    <div v-if="dataQueryAuditDetailInfoViewVisible" class="bi-panel bi-layout-content" style="height: calc(100% - 60px);">
      <v-request-detail
          :ida-guid="currRow.idaGuid"
          @updateCurrRow="updateCurrRow"
          :origin="origin"
          :res-guid="currRow.resGuid"
          :instance-guid="currRow.wfInstanceGuid"
          :visible.sync="dataQueryAuditDetailInfoViewVisible"
      >
      </v-request-detail>
    </div>


  </div>
</template>
<script>
import { inforesApi } from '@/api/irpApi';
import CreateDataQueryRequest from '@/views/dataqueryrequest/CreateDataQueryRequest'
import DataQueryAuditDetailInfo from "@/views/dataqueryrequest/DataQueryAuditDetailInfo";
export default {
  name: "DataQueryRequest",
  components:{
    // "v-infores-modify":InfoResModifyView,
    "v-request-create":CreateDataQueryRequest,
    "v-request-detail":DataQueryAuditDetailInfo,
  },
  data(){
    return {
      filterForm:{
        statusList:[]
      },
      flag:-1,
      statusList:[],
      currRow:{},
      currCheckedRow:{},
      queryList:[],
      createDataQueryRequestViewVisible:false,
      dataQueryAuditDetailInfoViewVisible:false,
      breadcrumbItems:[],
      pageSize:20,
      currPage:1,
      totalCount:0,
      loading:false,
      filterTimer:null,
      height: window.innerHeight - 219,
      origin:"1",
      // 是否为附加操作：  续期、重复提交
      isAttachAction: false,
      // 页面是否脏状态
      isDirty: false
    }
  },
  computed:{

  },

  watch: {
    // isDirty: function (n, o) {
    //   console.log("n,o :" ,n +"," + o)
    // },
    filterForm:{
      handler:function(){
        if(this.flag== 0){
          if(this.filterTimer != null){
            clearTimeout(this.filterTimer);
          }
          this.filterTimer = setTimeout(() =>{
            this.currPage =1 ;
            this.doFilter();
          },500);
        }
      },
      deep:true,
    },
    createDataQueryRequestViewVisible:{
      immediate:false,
      handler:function (newValue,oldValue) {
        if (newValue === false){
          // console.log("监视生效")
          // 面包屑 出栈
          this.breadcrumbItems.pop()
          this.isDirty = false
          // 回到主界面后进行刷新
          this.init()
        }
      }
    },
    dataQueryAuditDetailInfoViewVisible:{
      immediate:false,
      handler:function (newValue,oldValue) {
        if (newValue === false){
          this.breadcrumbItems.pop()
        }
      }
    }
  },
  mounted(){
    let _this = this;
    this.$nextTick(()=>{
      window.addEventListener('resize', () => { //监听浏览器窗口大小改变
        _this.height =window.innerHeight - 219;
      });
    })
    this.$BiTopWin.$.bi.ui.DIALOG_STYLE = "layui";
    this.init();
  },
  methods:{
    init(){
      this.flag =-1;
      inforesApi.getStatusList().then(res => {
        this.statusList = res.statusList;
        this.filterForm.statusList = [];
        res.statusList.forEach(statusItem => {
          this.filterForm.statusList.push(statusItem.label);
        })
        this.doFilter();
      })
      this.breadcrumbItems = []
    },
    //创建申请
    createQuery(){
      this.breadcrumbItems.push({
        title:'新建申请'
      })
      this.currRow = {}
      this.createDataQueryRequestViewVisible = true;
    },
    //编辑
    modifyClick(row,index){
        this.breadcrumbItems.push({
            title:'修改申请'
        })
        this.currRow = row;
        this.currRow.index = index;
        this.origin ="2"
        this.dataQueryAuditDetailInfoViewVisible = true;
    },
    //浏览
    browseClick(row,index){
      this.breadcrumbItems.push({
        title:'查看详情'
      })
      this.origin ="1"
      this.currRow = row;
      this.currRow.index = index;
      this.dataQueryAuditDetailInfoViewVisible = true;
    },
    //提交申请
    async submitPubClick(row,index){
      this.currRow = row;
      let data = {'idaGuid':row.idaGuid};
      await inforesApi.dataquerySubmit(data).then(res=>{
        this.updateRow(index,res.updatedRow);
      });
    },
    updateCurrRow:function(row){
        this.updateRow(this.currRow.index,row)
    },
    updateRow(index,updateData){
      this.queryList.forEach(item => {
        if(updateData.idaGuid.indexOf(item.idaGuid) != -1){
          this.$set(item,'resGuid',updateData.resGuid);
          this.$set(item,'idaGuid',updateData.idaGuid);
          this.$set(item,'reqResourceNumber',updateData.reqResourceNumber);
          this.$set(item,"status", updateData.status);
          this.$set(item,"statusTitle",updateData.statusTitle);
          this.$set(item,"auditUserTitle",updateData.auditUserTitle);
          this.$set(item,"validTime",updateData.validTime);
          this.$set(item,"wfInstanceGuid",updateData.wfInstanceGuid);
        }
      })
    },
    batchSubmit:function(){
      //选中行，待提交的
      let rows = this.$refs.queryListTable.selection;
      if(rows.length === 0 ){
        this.$BI.Dialog.warn("请选择可提交的资源！");
        return ;
      }
      let idaGuids =[];
      rows.forEach(row => {
        if(row.status === 10){
          idaGuids.push(row.idaGuid);
        }
      })
      if(idaGuids.length === 0 ){
        this.$BI.Dialog.warn("请重新选择可提交的资源！")
      }else{
        this.doBatchSubmit(idaGuids);
      }
    },
    doBatchSubmit(idaGuids){
      let data = {'idaGuids':JSON.stringify(idaGuids)};
      this.loading= true;
      inforesApi.dataqueryBatchSubmit(data).then((res) => {
        this.loading= false;
        this.$BI.Dialog.success(res.message);
        this.queryList.forEach(item => {
          if(idaGuids.indexOf(item.idaGuid) != -1){
            this.$set(item,"status", 20);
            this.$set(item,"statusTitle","审批中");
          }
        })
      });
    },
    //取回
    fetchBackClick(row,index){
      let datas={
        'idaGuid':row.idaGuid,
        'wfInstanceGuid':row.wfInstanceGuid
      }
      inforesApi.dataqueryFetchBack(datas).then(res => {
        this.updateRow(index,res.updatedRow);
      })
    },
    //续期
    renew(row,index){
      this.breadcrumbItems.push({
        title:'续期'
      })
      this.currRow = row;
      this.currRow.index = index;
      this.isAttachAction = true;
      this.createDataQueryRequestViewVisible = true
    },
    reSaveAndSubmit(row,index){
      this.breadcrumbItems.push({
        title:'重新提交'
      })
      this.currRow = row;
      this.currRow.index = index;
      this.isAttachAction = true;
      this.createDataQueryRequestViewVisible = true
    },
    //删除
    removeClick(row,index){
      this.doRemoveInfoRes(row,index);
    },
    //批量删除
    batchDelete:function(){
      let _this = this;
      //选中行，待提交的
      let rows = this.$refs.queryListTable.selection;
      if(rows.length === 0 ){
        this.$BI.Dialog.warn("请选择可删除的资源！");
        return ;
      }
      let idaGuids =[];
      rows.forEach(row => {
        if(row.status === 10 || row.status === 40){
          idaGuids.push(row.idaGuid);
        }
      })
      if(idaGuids.length === 0 ){
        this.$BI.Dialog.warn("请重新选择可删除的资源！")
      }else{
        this.$BI.Dialog.confirm("确定删除吗？", ()=>{
          _this.loading= true;
          inforesApi.dataqueryBatchDelete({'idaGuids':JSON.stringify(idaGuids)}).then((res) =>{
            _this.loading = false;
            if(res.success){
              _this.$BI.Dialog.msg("删除成功", { type: "success" });
              _this.doFilter();
            }else{
              _this.$BI.Dialog.msg("删除失败", { type: "error" });
            }
          }).catch(() => {
            _this.loading = false;
          });
        })
      }
    },
    doRemoveInfoRes(row,index){
      let that = this
      let params= {'idaGuid': row.idaGuid};
        this.$BI.Dialog.confirm("确定删除吗？", ()=>{
          inforesApi.dataqueryDelete(params).then(() => {
            that.queryList.splice(index, 1);
            that.totalCount = this.totalCount - 1;
          });
        })
    },
    doFilter(){
      this.loading = true;
      let datas = {
        statusList:JSON.stringify(this.filterForm.statusList),
        pageIndex:this.currPage,
        pageSize:this.pageSize
      }
      inforesApi.dataqueryFilterGet(datas).then(res => {

        // 任何状态类型都没有选择时，则列表置空
        if (res.byFilter - 0 === -1) {
          this.queryList = []
        }else {
          this.queryList = res.byFilter;
        }
        this.totalCount = res.count;
        this.$nextTick(() => {
          this.$refs.queryListTable.doLayout()
        })
        this.flag= 0;
        this.loading = false;
      })
    },
    pageSizeChange(val){
      // eslint-disable-next-line no-console
      this.pageSize= val;
      this.doFilter();

    },
    currentPageChange(val){
      // eslint-disable-next-line no-console
      this.currPage = val;
      this.doFilter();
    },
    indexMethod(index){
      return (this.currPage-1)*this.pageSize + 1 +index;
    },
    tableRowClick(row,column,event){
      if(this.$(event.target) && this.$(event.target).parent().attr("class").indexOf("bi-el-btn-text") != -1){
        return;
      }
      this.$refs.queryListTable.toggleRowSelection(row);
    },
    //查看申请详情
    numberInformationClick:async function (resGuidArr,idaGuid){
      //组装表格展示数据
      let result = await inforesApi.getGridInfoByResGuids({'resGuidArr':resGuidArr,'idaGuid':idaGuid})
      // 开发环境
      let url = this.$rootUrl+"/ires/selectedDataStatistic/selectedDataStatisticalDetailsBiDialog";
      // 生产环境，this.$BiTopWin为获取最顶层窗口，此处仅做示例。
      // let url = this.$BiTopWin.$.bi.getContextPath() + "/test/index.html#/selectedDataStatisticalDetailsBiDialog";

      // 定义BI弹出框配置项，具体参数详见jquery/widget/dialog/bi.ui.opendialog.impl.js；
      let options = {
        id:'selectedDataStatisticalDetailsBiDialog',
        title:"申请资源列表",
        width: 800,
        height: 500,
        draggable: true,
        showMax: true,
        resizable: true,
        url: url,
        initValue:result,
        returnValueFunctionName: 'confirmHandle',
        confirmCallback: this.confirmCallback,
        cancelCallback: this.cancelCallback
      }
      this.$BiTopWin.$.bi.ui.frameDialog(options);
    },
  
    //返回主页
    backToIndex () {
      if (this.breadcrumbItems.length === 0) {
        return;
      }
      if (this.createDataQueryRequestViewVisible) {
        if (this.isDirty) {
          this.$refs.refOfcreateRequest.backClick()
        } else {
          //可能保存过
          this.init()
          this.createDataQueryRequestViewVisible = false
        }
      }
      if (this.dataQueryAuditDetailInfoViewVisible) {
        this.dataQueryAuditDetailInfoViewVisible = false
      }
    }
  }
}
</script>

<style scoped>
#topOperate{
  display: inline-block;
  /*border: 1px red solid;*/
  width: 273px;
}
#fliterForm{
  display: inline-block;
  /*border: 1px red solid;*/
  width: 500px;
}
#fliterForm .el-form--inline .el-form-item{
  margin-right: 24px;
}
#fliterForm .el-form-item .el-form-item{
  margin-right: 0px;
}

.not-allow-click:hover{
  cursor: default;
  color:#222;
}
</style>
